﻿namespace Blaze.UI
{
    using UnityEngine;

    [ExecuteInEditMode]
    public class UILayerOrder : MonoBehaviour
    {
        public bool IncludeRenderer;

        public bool IncludeUI;

        public int Order
        {
            get => order;
            set
            {
                if (order == value)
                    return;
                order = value;
                UpdateLayer();
            }
        }

        public void UpdateLayer()
        {
            var finalOrder = mParent.Order + Order;
            if (IncludeRenderer)
            {
                var renders = GetComponentsInChildren<Renderer>();
                foreach (var render in renders)
                    render.sortingOrder = finalOrder;
            }

            if (IncludeUI)
            {
                var canvas = GetComponent<Canvas>();
                if (canvas == null)
                {
                    canvas = gameObject.AddComponent<Canvas>();
                    canvas.overrideSorting = true;
                }
                canvas.sortingOrder = finalOrder;
            }
        }

        private void Start()
        {
            mParent = GetComponentInParent<UILayer>();
            if (mParent != null)
                mParent.Add(this);
        }

        private void Update()
        {
            if (mParent == null)
            {
                mParent = GetComponentInParent<UILayer>();
                if (mParent != null)
                    mParent.Add(this);
                return;
            }

            if (!transform.IsChildOf(mParent.transform))
            {
                mParent.Remove(this);
                mParent = null;
            }

#if UNITY_EDITOR
            UpdateLayer();
#endif
        }

        [Tooltip("自定义UI元素层级")]
        [SerializeField]
        private int order;

        private UILayer mParent;
    }
}